package com.knowledgegraph.security;

import com.knowledgegraph.service.UserService;
import com.knowledgegraph.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    @Lazy
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        
        String requestPath = request.getRequestURI();
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        
        log.info("JWT过滤器 - requestURI: {}, contextPath: {}, servletPath: {}", requestPath, contextPath, servletPath);
        
        // 跳过公开接口 - 只有登录和注册等接口不需要认证
        if (isPublicEndpoint(servletPath)) {
            log.info("跳过公开接口: {}", requestPath);
            filterChain.doFilter(request, response);
            return;
        }
        
        try {
            String jwt = getJwtFromRequest(request);
            
            if (StringUtils.hasText(jwt) && jwtUtil.validateToken(jwt)) {
                Long userId = jwtUtil.getUserIdFromToken(jwt);
                
                UserDetails userDetails = userDetailsService.loadUserById(userId);
                UsernamePasswordAuthenticationToken authentication = 
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception ex) {
            log.error("无法设置用户认证", ex);
        }
        
        filterChain.doFilter(request, response);
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader(jwtUtil.getHeader());
        return jwtUtil.getTokenFromHeader(bearerToken);
    }
    
    /**
     * 判断是否为公开端点（不需要认证）
     */
    private boolean isPublicEndpoint(String path) {
        // 只有这些接口不需要认证
        return path.equals("/auth/login") ||
               path.equals("/auth/register") ||
               path.equals("/auth/check-username") ||
               path.equals("/auth/check-email") ||
               path.equals("/auth/reset-password") ||
               path.startsWith("/health/") ||
               path.startsWith("/public/") ||
               path.startsWith("/druid/") ||
               path.startsWith("/uploads/") ||
               path.startsWith("/static/");
    }
}